package com.wswy.wzcx.ui.main.community.detail

import android.arch.lifecycle.Observer
import android.content.Context
import android.content.Intent
import android.graphics.Rect
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.text.TextUtils
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.api.BaseResult
import com.che.libcommon.api.SimpleResultObserver
import com.che.libcommon.api.page.Pagination
import com.che.libcommon.ui.VOMessage
import com.che.libcommon.ui.loading.ILoadingView
import com.che.libcommon.utils.RxBus
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.api.Api
import com.wswy.wzcx.model.DataCenter
import com.wswy.wzcx.model.topic.CommentModel
import com.wswy.wzcx.model.topic.TopicModel
import com.wswy.wzcx.module.InternalMsgCode
import com.wswy.wzcx.module.base.CBaseLoadingActivity
import com.wswy.wzcx.module.base.Func1
import com.wswy.wzcx.statistics.StatTools
import com.wswy.wzcx.statistics.StatisticsId
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.main.community.TopicVO
import kotlinx.android.synthetic.main.activity_topic_detail.*
import kotlinx.android.synthetic.main.layout_app_title.*

class TopicDetailActivity : CBaseLoadingActivity(),Toolbar.OnMenuItemClickListener {


    override fun getConfigure(): ILoadingView.LoadingConfigure ? = null

    override fun getRootLayoutViewId() = R.id.rl_root

    override fun getLoadingFrameId() = R.id.fl_content


    companion object {

        private const val SHOW_IME = "showIME"

        fun start(context: Context,topicModel: TopicModel){

            Intent(context, TopicDetailActivity::class.java).run {
                putExtra(Constants.EXTRA_DATA,topicModel)

                context.startActivity(this)
            }


        }

        fun start(context: Context,topicId:Long,showIME:Boolean = false){
            Intent(context, TopicDetailActivity::class.java).run {
                putExtra(Constants.EXTRA_DATA_ID,topicId)
                putExtra(SHOW_IME,showIME)
                context.startActivity(this)
            }
        }

    }

    private lateinit var commentViewModel: CommentViewModel

    private lateinit var llManager: LinearLayoutManager

    private lateinit var adapter:CommentAdapter

    private var holderLoginCallback : Func1 = null

    private var showIME: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_topic_detail)
        setAppTitle("吐槽详情")
        val topic = intent?.getParcelableExtra<TopicModel?>(Constants.EXTRA_DATA)
        val topicId = intent?.getLongExtra(Constants.EXTRA_DATA_ID,0)?:0

        showIME = intent?.getBooleanExtra(SHOW_IME,false)?:false

        if (topic == null && topicId == 0L){
            finish()
            return
        }



        setSupportActionBar(toolbar)
        toolbar.setOnMenuItemClickListener(this)

        supportActionBar?.run {
            setDisplayShowTitleEnabled(false)
            setDisplayHomeAsUpEnabled(false)
            setDisplayShowHomeEnabled(false)
        }


        commentViewModel = provideViewModel(CommentViewModel::class.java)
        commentViewModel.onCreate()


        init()

        showLoading(true)


        topic?.run {
            commentViewModel.load(this)
        }
        if (topicId > 0){
            commentViewModel.load(topicId)
        }

        llManager = LinearLayoutManager(this)
        recycler_view.layoutManager = llManager


        recycler_view.addItemDecoration(object:RecyclerView.ItemDecoration(){
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)
                val pos = parent.getChildAdapterPosition(view)
                if (pos == 0){
                    outRect.top = SizeUtils.dp2px(10f)
                }else{
                    outRect.top = 0
                }
            }
        })


        adapter= CommentAdapter({

            commentViewModel.gotoLogin(this)

            holderLoginCallback = it

            null

        },View.OnClickListener {

            //点击评论

            StatTools.sendClick(it.context,StatisticsId.bbs_detail_comment_icon)

            KeyboardUtils.showSoftInput(et_comment)

        },
                commentViewModel.pagination as? Pagination<Any?>?)

        recycler_view.adapter = adapter



        btn_submit.setOnClickListener {

            val content=et_comment.text?.toString()

            if (TextUtils.isEmpty(content)){

                ToastUtils.showText("请输入评论")

                return@setOnClickListener
            }

            KeyboardUtils.hideSoftInput(et_comment)


            if (commentViewModel.isSending()){
                ToastUtils.showText("发送中请稍后")
                return@setOnClickListener
            }

            if (commentViewModel.hasLogin()){
                commentViewModel.addComment(content)
            }else{

                holderLoginCallback = {
                    commentViewModel.addComment(content)
                }
                commentViewModel.gotoLogin(this)

            }

        }


        et_comment.setOnClickListener {
            StatTools.sendClick(it.context,StatisticsId.bbs_detail_comment_box)
        }

    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        if (canShowMenu()){
            menuInflater.inflate(R.menu.menu_topic_detail, menu)
        }
        return super.onCreateOptionsMenu(menu)
    }



    override fun onMenuItemClick(item: MenuItem?): Boolean {
        when (item?.itemId) {
            R.id.action_delete -> {

                AlertDialog.Builder(this).apply {

                    setTitle(R.string.alert)

                    setMessage("是否确认要删除？")

                    setNegativeButton(R.string.cancel,null)

                    setPositiveButton(R.string.confirm_delete){_,_ ->
                        //删除
                        commentViewModel.getTopic()?.run {
                            doDelete(this)
                        }

                    }

                }.run {
                    show()
                }

            }
        }
        return true
    }



    private fun doDelete(topicModel: TopicModel){


        Api.get().topicDelete(topicModel.id).subscribe(object : SimpleResultObserver(){
            override fun onSuccess() {
                ToastUtils.showText("删除成功！")


                RxBus.getDefault().postWithCode(InternalMsgCode.CODE_TOPIC_DELETE,topicModel)

                finish()
            }

            override fun onApiError(result: BaseResult<*>?) {
                toastErrorMsg(result)
            }

        })

    }


    private fun canShowMenu():Boolean{
        val id = DataCenter.get().userMode?.userAlias;
        return !TextUtils.isEmpty(id)  && TextUtils.equals(id,commentViewModel.getTopic()?.userId)
    }

    private fun init(){

        commentViewModel.getUserLiveData().observe(this, Observer {

            it?.run {
                holderLoginCallback?.invoke()

                invalidateOptionsMenu()

            }

        })


        commentViewModel.getCommentsLiveData().observe(this, Observer {


            it?.run {


                if (isOk()){
                    showData()
                    if (isFirst()){
                        //第一次加载成功

                        //显示输入框，弹出输入法
                        ll_bottom.visibility = View.VISIBLE

                        invalidateOptionsMenu()
                        adapter.setNewData(data)

                        if (showIME){
                            KeyboardUtils.showSoftInput(et_comment)
                        }

                    } else if(payload == 100){

                        StatTools.sendClick(applicationContext,StatisticsId.bbs_detail_comment_tj)

                        data?.run {
                            adapter.datas?.addAll(2,data)
                        }

                        commentViewModel.getTopic()?.run {
                            RxBus.getDefault().postWithCode(InternalMsgCode.CODE_TOPIC_COMMIT,this)
                        }

                        //发布吐槽评论成功
//                        (data?.firstOrNull() as? CommentModel)?.run {
//                            RxBus.getDefault().postWithCode(InternalMsgCode.CODE_TOPIC_COMMIT,this)
//                        }

                        llManager.scrollToPosition(adapter.itemCount-1)
                        et_comment.text = null

                        //刷新数据
                        (adapter.getItemData(0) as? TopicVO)?.run {
                            reply++
                        }

                        (adapter.getItemData(1) as? String)?.toIntOrNull()?.run {
                            adapter.datas?.set(1,inc().toString())
                        }


                    }else{
                        //普通 加载下一页
                        adapter.addData(data)
                    }


                    adapter.notifyDataSetChanged()

                    if (payload == 100){
                        llManager.scrollToPosition(1)
                    }

                }else if (isFirst() && hasError()){
                    //错误
                    if (errorCode == 1){
                        finish()
                    }else{
                        showError(VOMessage.createEmpty(R.drawable.messages_default_empty,R.string.error_common,0))
                    }
                }

            }

        })

    }

    override fun onPause() {
        super.onPause()
        KeyboardUtils.hideSoftInput(this)
    }

}